import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile } from '@ffmpeg/util';

const ffmpeg = new FFmpeg();

async function loadFFmpeg() {
	if (!ffmpeg.loaded) {
		await ffmpeg.load({
			coreURL: 'https://unpkg.com/@ffmpeg/core@0.12.6/dist/ffmpeg-core.js', // 核心文件 URL
		});
	}
}

async function compressVideo(base64, mimeType) {
	await loadFFmpeg();

	const inputName = 'input.mp4';
	const outputName = 'output.mp4';

	// 将 Base64 转换为 Blob
	const blob = base64ToBlob(base64, mimeType);

	// 将 Blob 写入 FFmpeg
	await ffmpeg.writeFile(inputName, await fetchFile(blob));

	// 执行压缩命令
	await ffmpeg.exec(['-i', inputName, '-vf', 'scale=640:-1', '-b:v', '500k', outputName]);

	// 读取压缩后的视频
	const data = await ffmpeg.readFile(outputName);
	const compressedBlob = new Blob([data], { type: mimeType });

	// 将压缩后的 Blob 转换为 Base64
	return await blobToBase64(compressedBlob);
}

function base64ToBlob(base64, mimeType) {
	const byteCharacters = atob(base64.split(',')[1]);
	const byteArrays = [];

	for (let offset = 0; offset < byteCharacters.length; offset += 512) {
		const slice = byteCharacters.slice(offset, offset + 512);
		const byteNumbers = new Array(slice.length);
		for (let i = 0; i < slice.length; i++) {
			byteNumbers[i] = slice.charCodeAt(i);
		}
		const byteArray = new Uint8Array(byteNumbers);
		byteArrays.push(byteArray);
	}

	return new Blob(byteArrays, { type: mimeType });
}

function blobToBase64(blob) {
	return new Promise((resolve) => {
		const reader = new FileReader();
		reader.onloadend = () => resolve(reader.result);
		reader.readAsDataURL(blob);
	});
}

export { compressVideo };